import "./style.less";
import { VC, Component, Prop } from "@/VC-vue";
import IForm from "@/components/Form";
import { Column } from "@/types/column";
import { FormUtils } from "@/types/form-ref";
import { IFormItem } from "@/types/form-item";
import { ITable } from "@/components/Table";
import { Table } from "@/types/table";

export interface ITableData {
    dataSource: Array<{}>;
    totalSize: number;
}

export interface ITableProps {
    columns: ((t: ListPage) => Column[]) | Column[];
    algin?: string;
    searchItems?: IFormItem[];
    actions?: (t: ListPage) => JSX.Element[];
    customRow?: (...arg: any) => {};
    tableProps?: Omit<Table, "columns" | "customRow" | "dataSource">;
    fetch?(arg: {}): Promise<ITableData>;
    fetchData?: any;
    query?: any;
    showSelect?: boolean;
    scroll?: any;
    tableData?: any;
}

@Component({})
export class ListPage extends VC<ITableProps> {
    @Prop() columns!: ((t: ListPage) => Column[]) | Column[];
    @Prop() fetch!: (arg: {}) => Promise<ITableData>;
    @Prop() query?: (params: {}) => Promise<[]>;
    @Prop() searchItems?: any[];
    @Prop() actions?: (t: ListPage) => JSX.Element[];
    @Prop() tableProps?: any;
    @Prop() customRow?: (...arg: any) => {};
    @Prop() fetchData?: any;
    @Prop() showSelect?: any;
    @Prop() tableData?: any;

    isUp = false;
    totalSize = 0;
    totalPage = 0;
    loading = false;
    selectList = [];
    currentPage = 1;
    dataSource: any[] = [];
    pageSize: any = 10;
    searchData: any = null;

    get rowSelection() {
        return {
            selectedRowKeys: this.selectList,
            onChange: (selectedRowKeys: any) => {
                this.selectList = selectedRowKeys;
            }
        };
    }
    get pagination() {
        return {
            current: this.currentPage,
            showTotal: n => {
                return "共" + this.totalSize + "条";
            },
            total: this.totalSize,
            showSizeChanger: true,
            showQuickJumper: true,
            defaultPageSize: this.pageSize,
            onChange: n => this.getData(n).then(_ => (this.currentPage = n)),
            onShowSizeChange: (n, size) => {
                this.pageSize = size;
                return this.getData(1, size).then(_ => (this.currentPage = 1));
            }
        };
    }

    created() {
        this.getData();
    }

    async getData(n = 1, size = 10) {
        this.loading = true;
        if (!this.$props.fetch) {
            this.dataSource = this.tableData;
            this.totalSize = this.tableData.length;
            this.loading = false;
            return;
        }
        let data;
        if (this.fetchData) {
            data = Object.assign(this.fetchData, {
                startPage: n,
                pageSize: this.pageSize
            });
            if (this.searchData) {
                data = {
                    startPage: n,
                    pageSize: this.pageSize,
                    ...this.searchData
                };
            }
        } else if (this.searchData) {
            data = {
                startPage: n,
                pageSize: this.pageSize,
                ...this.searchData
            };
        } else {
            data = { startPage: n, pageSize: this.pageSize };
        }
        return this.$props.fetch(data).then(res => {
            this.dataSource = res.dataSource;
            this.totalSize = res.totalSize;
            this.loading = false;
            return true;
        });
    }

    /** 按条件查询 */
    _query(form: FormUtils) {
        const params: any = form.getFieldsValue();
        if (this.query) {
            this.loading = true;
            this.searchData = params;
            console.log(params);
            if (params.reconStartTime) {
                params.reconStartTime = params.reconStartTime.format(
                    "YYYY-MM-DD"
                );
            }
            if (params.reconEndTime) {
                params.reconEndTime = params.reconEndTime.format("YYYY-MM-DD");
            }
            this.query({
                ...params,
                startPage: 1,
                pageSize: this.pageSize
            })
                .then(v => {
                    this.dataSource = (v as any).dataSource;
                    this.totalSize = (v as any).totalSize;
                })
                .finally(() => (this.loading = false));
        }
    }
    /** 切换查询项展开收起 */
    toggleForm() {
        this.isUp = !this.isUp;
    }

    renderButton() {
        const buttonStyle = {
            marginLeft: "10px"
        };
        if (this.selectList.length > 0) {
            return <a-button style={buttonStyle}>批量操作</a-button>;
        }
    }
    /** 重置列表数据 & 搜索条件 */
    reload(form: FormUtils) {
        this.searchData = null;
        form && form.resetFields();
        this.getData().then(r => {
            this.currentPage = 1;
        });
    }

    get Search() {
        const items = this.searchItems;
        if (!items) {
            return;
        }
        items.map((r: any) => (r.style = "margin-right:20px;"));
        const handle = {
            el: (form: FormUtils) => (
                <div style="margin-left:30px;width:100%">
                    <a-button
                        style="margin-right:10px"
                        type="primary"
                        icon="search"
                        onClick={() => this._query(form)}
                    />
                    <a-tooltip title="刷新将会清除搜索条件。">
                        <a-button
                            style="margin-right:10px"
                            type="primary"
                            icon="sync"
                            onClick={() => this.reload(form)}
                        />
                    </a-tooltip>
                </div>
            )
        };
        return (
            <IForm
                layout="inline"
                id="header-search"
                col={{ lg: 10, md: 24, xl: 7, xxl: 4 }}
                itemList={[...items, handle]}
            />
        );
    }

    render() {
        const {
            columns,
            pagination,
            dataSource,
            rowSelection,
            loading,
            customRow
        } = this;
        const props = {
            pagination,
            rowSelection,
            loading,
            customRow,
            ...this.tableProps
        };
        const bodyStyle = {
            padding: "0 0 15px",
            borderRadius: 0,
            minHeight: "70px",
            border: 0
        };
        if (!this.showSelect) {
            props.rowSelection = null;
        }
        return (
            <div style="background:#fff;padding:25px;">
                <a-card
                    bodyStyle={bodyStyle}
                    bordered={false}
                    v-if={this.searchItems || this.actions}
                >
                    {this.Search}
                    {
                        <div class="is-flex">
                            {this.actions && this.actions(this)}
                            {this.renderButton()}
                        </div>
                    }
                </a-card>
                <ITable
                    scroll={this.$props.scroll}
                    {...{ props }}
                    dataSource={dataSource}
                    columns={
                        typeof columns === "function" ? columns(this) : columns
                    }
                />
            </div>
        );
    }
}
